import json
from django.http import HttpResponse
from .models import Holidays
from users.models import Staff
from django.core import serializers
import datetime
# Create your views here.


def fuck_cors(response):
    response["Access-Control-Allow-Origin"] = "http://localhost:4200"
    response['Access-Control-Allow-Credentials'] = 'true'
    response["Access-Control-Allow-Methods"] = "GET,POST,OPTIONS,PATCH"
    response["Access-Control-Allow-Headers"] = "Origin,Cookie,Accept,Token,Access-Control-Allow-Origin," \
                                               "Access-Control-Allow-Headers,X-Requested-With,Content-Type," \
                                               "Access-Control-Allow-Credentials, set-cookie"


def manager_get_holiday(request, ID=None):
    if ID:
        my_holidays = Holidays.objects.filter(id=ID)
    else:
        my_holidays = Holidays.objects.filter(status__lt=3, status__gte=0)
    my_holidays = serializers.serialize("json", my_holidays)
    return HttpResponse(content=my_holidays, content_type="application/json", status=200)


def applicants_get_holiday(request, ID = None):
    if ID:
        staff = Staff.objects.get(username=ID)
        my_holidays = Holidays.objects.filter(staffId_id=staff.id)
    else:
        my_holidays = Holidays.objects.all()
    my_holidays = serializers.serialize("json", my_holidays)
    return HttpResponse(content=my_holidays, content_type="application/json", status=200)


def insert_entry_holiday(request, username, res):
    req = json.loads(request.body)
    print(req)
    if username != req['staffId']:
        res['msg'] = '没有权限'
        return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=403)
    req['status'] = 0
    if len(req) != 7:
        res['msg'] = '数据项丢失'
        return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=422)
    staff = Staff.objects.get(username=username)
    if req['category'] == '年假':
        d1 = datetime.datetime.strptime(req['endTime'], '%Y-%m-%d')
        d2 = datetime.datetime.strptime(req['beginTime'], '%Y-%m-%d')
        staff.annualLeave -= (d1 - d2).days
        if staff.annualLeave < 0:
            res['msg'] = '年假剩余不足'
            return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json',
                                status=400)
    staff.save()
    req['staffId'] = staff
    print(req)
    # del req['username']
    Holidays.objects.create(**req)
    return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=200)


def applicants_update_holidays(request, username, res, ID):
    req = json.loads(request.body)
    if username != req['staffId']:
        req['msg'] = '没有权限'
        return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=403)
    if len(req) != 5:
        req['msg'] = '数据项丢失'
        return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=422)
    staff = Staff.objects.get(username=username)
    holiday = Holidays.objects.get(id=ID)
    if req['category'] == '年假':
        staff.annualLeave = staff.annualLeave + (holiday.endTime - holiday.beginTime) - (
                    req['endTime'] - req['beginTime'])
        if staff.annualLeave < 0:
            req['meg'] = '年假剩余不足'
            return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json',
                                status=400)
    staff.save()
    holiday.beginTime = req['beginTime']
    holiday.endTime = req['endTime']
    holiday.reason = req['reason']
    holiday.category = req['category']
    holiday.status = 0
    holiday.dManagerIdea = None
    holiday.vManagerIdea = None
    holiday.managerIdea = None
    holiday.save()
    holiday = Holidays.objects.filter(id=ID)
    holiday = serializers.serialize("json", holiday)
    return HttpResponse(content=holiday, content_type='application/json', status=200)


def managers_update_holidays(request, username, res, ID):
    req = json.loads(request.body)
    manager = Staff.objects.get(username=username)
    holiday = Holidays.objects.get(id=ID)
    staff = Staff.objects.get(id=holiday.staffId_id)
    print(req)
    if manager.position == '总经理':
        if holiday.status != 2:
            res['msg'] = '待部门经理或副总经理审批'
            return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=403)
        else:
            if req['flag'] == 'true':
                holiday.status = 3
            else:
                holiday.status = -1
                if holiday.category == '年假':
                    staff = Staff.objects.get(id=holiday.staffId_id)
                    staff.annualLeave += (holiday.endTime - holiday.beginTime).days
                    staff.save()
            holiday.managerIdea = req['reason']
            holiday.save()
            res = serializers.serialize("json", Holidays.objects.filter(id=ID))
            return HttpResponse(content=res, content_type='application/json', status=200)
    elif manager.position == '副总经理':
        if holiday.status < 1:
            res['msg'] = '待部门经理审批'
            return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=403)
        elif holiday.status >= 2:
            res['msg'] = '禁止审批'
            return HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=403)
        else:
            if req['flag'] == 'true':
                holiday.status = 2
            else:
                holiday.status = -1
                if holiday.category == '年假':
                    staff = Staff.objects.get(id=holiday.staffId_id)
                    staff.annualLeave += (holiday.endTime - holiday.beginTime).days
                    staff.save()
            holiday.managerIdea = req['reason']
            holiday.save()
            res = serializers.serialize("json", Holidays.objects.filter(id=ID))
            return HttpResponse(content=res, content_type='application/json', status=200)
    elif manager.position == '部门经理':
        if holiday.status >= 1 or manager.department != staff.department:
            res['msg'] = '禁止审批'
            return HttpResponse(content=json.dumps(res), content_type='application/json', status=403)
        else:
            print(req)
            print(req['flag'])
            if req['flag'] == 'true':
                holiday.status = 1
            else:
                holiday.status = -1
                if holiday.category == '年假':
                    staff = Staff.objects.get(id=holiday.staffId_id)
                    staff.annualLeave += (holiday.endTime - holiday.beginTime).days
                    staff.save()
            holiday.managerIdea = req['reason']
            holiday.save()
            res = serializers.serialize("json", Holidays.objects.filter(id=ID))
            return HttpResponse(content=res, content_type='application/json', status=200)
    else:
        res['msg'] = '禁止审批'
        return HttpResponse(content=json.dumps(res), content_type='application/json', status=403)


def holidays(request, role):
    if request.method == 'OPTIONS':
        response = HttpResponse(status=200)
        fuck_cors(response)
        return response
    username = request.session.get('username', None)
    print(request.session.session_key)
    print(username)
    res = {}
    if username:
        if role == "applicants":
            if request.method == "GET":
                response = applicants_get_holiday(request)
                fuck_cors(response)
                return response
            elif request.method == "POST":
                response = insert_entry_holiday(request, username, res)
                fuck_cors(response)
                return response
            else:
                res['msg'] = '请求方法不正确'
                response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=404)
                fuck_cors(response)
                return response
        elif role == "managers":
            if request.method == "GET":
                response = manager_get_holiday(request)
                fuck_cors(response)
                return response
            else:
                res['msg'] = '请求方法不正确'
                response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json',
                                    status=404)
                fuck_cors(response)
                return response
        else:
            response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='applications/json',
                                status=404)
            fuck_cors(response)
            return response
    else:
        res['msg'] = "用户未登陆"
        response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type="application/json", status=401)
        fuck_cors(response)
        return response


def holidays_single(request, role, ID):
    if request.method == 'OPTIONS':
        response = HttpResponse(status=200)
        fuck_cors(response)
        return response
    username = request.session.get('username', None)
    res = {}
    if username:
        if role == "applicants":
            if request.method == "GET":
                response = applicants_get_holiday(request, ID)
                fuck_cors(response)
                return response
            elif request.method == 'PATCH':
                response = applicants_update_holidays(request, username, res, ID)
                fuck_cors(response)
                return response
            else:
                res['msg'] = '请求方法不正确'
                response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json',
                                    status=404)
                fuck_cors(response)
                return response
        elif role == "managers":
            if request.method == "GET":
                response = manager_get_holiday(request, ID)
                fuck_cors(response)
                return response
            elif request.method == "PATCH":
                response = managers_update_holidays(request, username, res, ID)
                fuck_cors(response)
                return response
            else:
                res['msg'] = '请求方法不正确'
                response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json',
                                    status=404)
                fuck_cors(response)
                return response
        else:
            response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='applications/json',
                                status=404)
            fuck_cors(response)
            return response
    else:
        res['msg'] = "用户未登陆"
        response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type="application/json", status=401)
        fuck_cors(response)
        return response


def test(request):
    response = applicants_get_holiday(request)
    fuck_cors(response)
    return response


def test_insert(request):
    if request.method == 'POST':
        res = {}
        # request.META['CONTENT_TYPE'] = 'application/json'
        # print(request.META)
        print(request.body)
        req = json.loads(request.body)
        response = insert_entry_holiday(request, req['staffId'], res)
        fuck_cors(response)
        return response
    else:
        response = HttpResponse(content=json.dumps({'msg': 'option'}), content_type='application/json', status=404)
        fuck_cors(response)
        return response


def holidays_no_cookie(request, role):
    if request.method == 'OPTIONS':
        response = HttpResponse(status=200)
        fuck_cors(response)
        return response
    res = {}
    req = {}
    if request.method != 'GET':
        req = json.loads(request.body)
    username = req.get('username')
    if username or request.method == 'GET' or request.method == 'POST':
        if role == "applicants":
            if request.method == "GET":
                response = applicants_get_holiday(request)
                fuck_cors(response)
                return response
            elif request.method == "POST":
                response = insert_entry_holiday(request, username, res)
                fuck_cors(response)
                return response
            else:
                res['msg'] = '请求方法不正确'
                response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json', status=404)
                fuck_cors(response)
                return response
        elif role == "managers":
            if request.method == "GET":
                response = manager_get_holiday(request)
                fuck_cors(response)
                return response
            else:
                res['msg'] = '请求方法不正确'
                response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json',
                                    status=404)
                fuck_cors(response)
                return response
        else:
            response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='applications/json',
                                status=404)
            fuck_cors(response)
            return response
    else:
        res['msg'] = "用户未登陆"
        response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type="application/json", status=401)
        fuck_cors(response)
        return response


def holidays_single_no_cookie(request, role, ID):
    if request.method == 'OPTIONS':
        response = HttpResponse(status=200)
        fuck_cors(response)
        return response
    res = {}
    req = {}
    if request.method != 'GET':
        req = json.loads(request.body)
    username = req.get('username')
    if username or request.method == 'GET' or request.method == 'PATCH':
        if role == "applicants":
            if request.method == "GET":
                response = applicants_get_holiday(request, ID)
                fuck_cors(response)
                return response
            elif request.method == 'PATCH':
                response = applicants_update_holidays(request, username, res, ID)
                fuck_cors(response)
                return response
            else:
                res['msg'] = '请求方法不正确'
                response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json',
                                    status=404)
                fuck_cors(response)
                return response
        elif role == "managers":
            if request.method == "GET":
                response = manager_get_holiday(request, ID)
                fuck_cors(response)
                return response
            elif request.method == "PATCH":
                response = managers_update_holidays(request, username, res, ID)
                fuck_cors(response)
                return response
            else:
                res['msg'] = '请求方法不正确'
                response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='application/json',
                                    status=404)
                fuck_cors(response)
                return response
        else:
            response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type='applications/json',
                                status=404)
            fuck_cors(response)
            return response
    else:
        res['msg'] = "用户未登陆"
        response = HttpResponse(content=json.dumps(res, ensure_ascii=False), content_type="application/json", status=401)
        fuck_cors(response)
        return response
